package nio.two;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/*
    NIO下的通信入门案例---客户端
 */
public class Client {
    public static void main(String[] args) {
        try {
            //创建客户端通道
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost",9999));
            socketChannel.configureBlocking(false);
            Scanner scanner = new Scanner(System.in);
            //创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            String str = "";
            while (true){
                str = scanner.nextLine();
                buffer.put(("某个客户端："+str).getBytes());
                //将缓冲区设置为读模式，并将消息发送给服务端
                buffer.flip();
                socketChannel.write(buffer);
                //清空缓冲区
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
